from PIL import Image, ImageEnhance, ImageOps
import pytesseract
import os
import requests
import re
import time
import threading
# import subprocess

# 涉及技术：
'''
adb截取手机屏幕，保存到电脑
处理截屏图片，通过点的颜色判断是否是答题界面
将答题界面分成题目区域和选项区域
使用pytesseract库识别图片文字
    pytesseract依赖PIL及tesseract-ocr。
    其中PIL为图像处理库，而后面的tesseract-ocr则为google的ocr识别引擎
为了提高识别图片速度，采用多线程
线程一查询题目，并使用线程二处理的选项列表（全局变量）
线程中加锁，防止选项列表未构建好的情况下搜索答案（上一题的选项匹配后一道题）
'''
# 获取选项的线程总比查询题目线程出现的快，因为题目线程需要百度
# 所以我要在查询百度后再执行选项遍历
choices_list = []


# 二值化算法
def binarizing(img,threshold):
    pixdata = img.load()
    w, h = img.size
    for y in range(h):
        for x in range(w):
            if pixdata[x, y] < threshold:
                pixdata[x, y] = 0
            else:
                pixdata[x, y] = 255
    return img

# 一直截屏
def get_screen(num):
    if num == 1:
        os.system('adb shell screencap -p /sdcard/screenshot1.png')
        os.system('adb pull /sdcard/screenshot1.png .')
        # time.sleep(0.2)
    elif num == 2:
        os.system('adb shell screencap -p /sdcard/screenshot2.png')
        os.system('adb pull /sdcard/screenshot2.png .')
        # time.sleep(0.2)

# 1为出题界面，2为出现选项的界面
def start(num):
    color = ''
    color2 = ''
    x = tuple()
    y = (68, 82, 163, 255)
    if num == 1:
        image = Image.open('./screenshot1.png')
        x = (242, 89, 75, 255)
        color = image.getpixel((615, 349))
        color2 = image.getpixel((543, 543))
    elif num == 2:
        image = Image.open('./screenshot2.png')
        x = (255, 255, 255, 255)
        color = image.getpixel((768, 981))
        color2 = image.getpixel((543, 543))
    if color == x and color2 == y:
        return 1
    else:
        return 0

# 处理图片读出文字，返回文字
def handle_pic(pic):
    # 图片增强
    pic = ImageEnhance.Contrast(pic).enhance(1.8)
    # 转化为灰度图
    pic = pic.convert('L')
    # 把图片变成二值图像
    pic = binarizing(pic, 190)
    tessdata_dir_config = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata" --psm 6'
    text = pytesseract.image_to_string(pic, lang='chi_sim', config=tessdata_dir_config)
    text = text.replace(' ', '')
    return text

# 百度问题，返回的文本存入text
def baidu_question(question):
    # 百度查询问题，返回整理后的页面内容（字符串）
    kw = {'wd': question}
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
    response = requests.get("http://www.baidu.com/s?", params=kw, headers=headers)
    response_content = response.text
    p = re.compile(r'<.*?>|".*?":".*?"|"http://.*?"|{.*?}|&.*?;|\s|\t|\n|\r|&nbsp;| ')
    s = p.sub('', response_content)
    return s

# 返回问题字符串
def get_question():
    image = Image.open('./screenshot1.png')
    # 问题区截图
    question = image.crop((18, 591, 1058, 865))
    question_text = handle_pic(question)
    question_text = question_text.replace('\n', '')
    question_text = question_text.replace('罡', '是')
    print(question_text)
    return question_text

# 返回选项列表
def get_choices():
    image = Image.open('./screenshot2.png')
    # 选项区截图
    choices = image.crop((250, 969, 829, 1684))
    choices_text = handle_pic(choices)
    p = re.compile(r'\n|\r|_|-|一|—')
    s = p.sub(' ', choices_text)
    text_list = s.split(' ')
    global choices_list
    choices_list = text_list

def handle_question():
    while 1:
        get_screen(1)
        start_true = start(1)
        if start_true:
            # 获取文本
            question_w = get_question()
            if question_w:
                # 搜索问题
                result = baidu_question(question_w)
                mutex.acquire(True)
                global choices_list
                print('choices_list:', choices_list)
                for i in choices_list:
                    if i:
                        num = result.count(i)
                        print(i, ':', num)
                mutex.release()

def handle_choices():
    while 1:
        get_screen(2)
        start_true = start(2)
        if start_true:
            # 构造选项列表
            mutex.acquire(True)
            get_choices()
            mutex.release()

if __name__ == '__main__':
    mutex = threading.Lock()
    # 查题线程
    t1 = threading.Thread(target=handle_question)
    # 读取选项
    t2 = threading.Thread(target=handle_choices)

    t1.start()
    t2.start()

